<template>
  <div class="pages unifiedpricemanagement">
    <div class="pageLevel" v-if="!sub">
      <!-- 搜索框 -->
      <div class="tableSearch">
        <el-form label-width="90px" class="demo-ruleForm">
          <el-form-item label label-width="15">
            <el-input
              placeholder="请输入商品名称搜索"
              v-model="clientsalePrice.shopName"
              size="small"
              style="width:200px;"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品品牌:" label-width="100px">
            <el-select
              size="small"
              filterable
              style="width:190px"
              v-model="clientsalePrice.brandId"
              placeholder="请先选择商品品牌"
            >
              <el-option label="全部" value></el-option>
              <el-option
                v-for="(item,index) in commodityBrandList"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户类型:" prop="shopTypeIds" class="shop-type-wrap">
            <el-select
              v-model="clientsalePrice.shopTypeIds"
              placeholder="请选择"
              size="small"
              style="width:190px"
            >
              <el-option label="全部" value></el-option>
              <el-option
                v-for="item in shopTypesList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label label-width="20px">
            <el-button type="primary" size="mini" @click="counsearch" class="Button">查询</el-button>
          </el-form-item>
          <el-form-item label label-width="20px">
            <el-button type="primary" size="mini" @click="update">批量更新</el-button>
          </el-form-item>

          <el-form-item label label-width="20px">
            <!-- v-if="setRole('导出')" -->
            <el-button type="primary" size="mini" class="Button" @click="download">导出当前查询结果</el-button>
          </el-form-item>
          <el-form-item label label-width="20px">
            <el-button type="primary" size="mini" @click="routerPush()">调价审核记录</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 表格 -->
      <div class="tableMain">
        <el-table :data="pricemange.tableData" stripe style="width: 100%">
          <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
          <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
          <el-table-column prop="primaryClassifyName" label="分类" align="center"></el-table-column>
          <el-table-column prop="goodsLabelName" label="商品品牌" align="center"></el-table-column>
          <el-table-column prop="goodsName" label="商品名称" align="center"></el-table-column>
          <el-table-column prop="goodsSpec" label="规格型号" align="center">
            <template slot-scope="scope">
              <div v-for="(item,index) in scope.row.goodsSpec" :key="index">
                <span v-if="item!=null">{{item.paramName}} :</span>
                <span v-if="item!=null">{{item.paramValue}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="goodsUnit" label="单位" align="center"></el-table-column>
          <el-table-column prop="price" label="期间价格" align="center"></el-table-column>
          <el-table-column prop="shopTypeName" label="客户类型" align="center"></el-table-column>
          <el-table-column prop="entryTime" label="生效期间" align="center" width="200">
            <template slot-scope="scope">
              <div v-for="(item,index) in scope.row.entryTime" :key="index">
                <span>{{item.startDate}}</span>-
                <span>{{item.endDate}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="name" align="center" label="操作" width="180">
            <template slot-scope="scope">
              <el-button
                size="small"
                @click="_pricehistory(scope.$index,scope.row)"
                type="text"
                class="addDetail"
              >调价历史</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 页码 -->
        <page-unit :pageData="pricemange.pageData" :func="_pricemangeListPage"></page-unit>
      </div>
    </div>

    <div class="pageLevel" v-else>
      <router-view></router-view>
    </div>
    <!-- 调价历史弹窗 -->
    <el-dialog title="调价历史" :visible.sync="orderTable.dialog" class="addshopname">
      <!-- 新增调价开始 -->
      <el-dialog
        width="35%"
        title="新增调价"
        :visible.sync="addprice.dialog"
        append-to-body
        class="addshopname"
      >
        <i class="el-icon-close icon" @click="addprice.dialog = false,resetForm('ruleForm')"></i>
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="生效期间：" prop="effectiveperiod" >
            <el-date-picker
              size="small"
              :clearable="false"
              v-model="ruleForm.effectiveperiod"
              format="yyyy年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="期间价格：" prop="interimprice">
            <el-input v-model="ruleForm.interimprice" size="small"></el-input>
            <span>元</span>
          </el-form-item>
          <el-form-item label="调价原因：" prop="pricereason">
            <textarea
              maxlength="20"
              v-model="ruleForm.pricereason"
              name
              id
              cols="10"
              rows="5"
              style="width:220px;resize:none;border-radius:5px;"
            ></textarea>
          </el-form-item>
          <!-- <span>注：若审核日期在生效日期内，则期间价格在下一个自然日开始时生效</span> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addprice.dialog = false,resetForm('ruleForm')" size="small">取 消</el-button>
          <el-button
            type="primary"
            @click="submitForm('ruleForm')"
            :disabled="submin"
            size="small"
          >提 交</el-button>
        </div>
      </el-dialog>
      <!-- 新增调价结束 -->
      <i class="el-icon-close icon" @click="orderTable.dialog = false"></i>
      <div style="margin-top:-10px;">
        <el-row style="height:30px;">
          <el-col :span="6">
            <span>商品条码：</span>
            <span>{{hispricelist.barCode}}</span>
          </el-col>
          <el-col :span="6">
            <span>商品货号：</span>
            <span>{{hispricelist.goodsCode}}</span>
          </el-col>
          <el-col :span="6">
            <span>商品分类：</span>
            <span>{{hispricelist.primaryClassifyName}}</span>
          </el-col>
          <el-col :span="6">
            <span>商品品牌：</span>
            <span>{{hispricelist.goodsLabelName}}</span>
          </el-col>
        </el-row>
        <el-row style="height:30px;">
          <el-col :span="6">
            <span>商品名称：</span>
            <span>{{hispricelist.goodsName}}</span>
          </el-col>
          <el-col :span="6">
            <span>规格型号：</span>
            <div
              v-for="(item,index) in hispricelist.goodsSpec"
              :key="index"
              style="display:inlin-block;"
            >
              <span>{{item.paramName}}</span>
              <span>{{item.paramValue}}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <span>单位：</span>
            <span>{{hispricelist.goodsUnit}}</span>
          </el-col>
          <el-col :span="6">
            <span>客户类型：</span>
            <span>{{hispricelist.shopTypeName}}</span>
          </el-col>
        </el-row>
        <el-row style="height:30px;">
          <el-col :span="6">
            <span>当前统一价格：</span>
            <span>{{hispricelist.price}}元</span>
          </el-col>
          <el-col :span="6">
            <span>申请人：</span>
            <span>{{users}}</span>
          </el-col>
        </el-row>
      </div>
      <el-button
        type="primary"
        style="float:right;margin-right:40px;
      margin-bottom:20px;"
        size="mini"
        @click="addpriceButton"
      >新增调价</el-button>
      <div class="tableMain pltable">
        <el-table
          :data="orderTable.tableData"
          :row-class-name="tableRowClassName"
          stripe
          style="width: 100%"
        >
          <el-table-column prop="code" label="编号" align="center"></el-table-column>
          <el-table-column prop="entryTime" label="生效期间" align="center">
            <template slot-scope="scope">
              <div v-for="(item,index) in scope.row.entryTime" :key="index">
                <span>{{item.startDate}}</span>-
                <span>{{item.endDate}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="期间价格" align="center"></el-table-column>
          <el-table-column prop="status" label="期间价格状态" align="center" width="150">
            <template slot-scope="scope">
              <div>{{pricestatusList[scope.row.status]}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="creater" label="申请人" align="center"></el-table-column>
          <el-table-column prop="createTime" :formatter="tim1" label="添加日期" align="center"></el-table-column>
          <el-table-column prop="name" align="center" label="操作" width="180">
            <template slot-scope="scope">
              <el-button
                size="small"
                @click="deletes(scope.$index,scope.row)"
                type="text"
                class="delete"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 页码 -->
        <!-- <page-unit :pageData="orderTable.pageData" :func="_pricehistoryListPage"></page-unit> -->
      </div>
      <!-- <div slot="footer" class="dialog-footer">
        <el-button @click="orderTable.dialog = false" size="small">取 消</el-button>
        <el-button type="primary" @click="innerVisible = true" size="small">确 定</el-button>
      </div>-->
    </el-dialog>
    <!-- 批量更新弹窗 -->
    <el-dialog title="批量更新" :visible.sync="batchUpdate.dialog" class="addshopname">
      <!-- 上传中弹窗 -->
      <el-dialog width="30%" append-to-body :visible.sync="uploadin.dialog" class="uploadin">
        <div class="uploadintext">上传中</div>
        <div>
          <el-progress :text-inside="true" :stroke-width="20" :percentage="speedofprogress"></el-progress>
        </div>
      </el-dialog>
      <i class="el-icon-close icon" @click="_cancel"></i>
      <div style="margin-top:-10px;">
        <ul class="updatetext">
          <span>使用说明：</span>
          <li>1.将需要修改价格的商品或全部商品导出,首次编辑请全部导出;</li>
          <li>2.请按照导出数据模板的格式准备导入数据，模板中的表头名称不可更改，表头行不能删除;</li>
          <li>3.只需修改生效期间、期间价格列内数据。</li>
          <span>请选择需要导入的Excel文件</span>
          <a href="javascript:;" class="file">
            {{value}}
            <input
              id="fileupload"
              placeholder="请选择文件"
              ref="uploading"
              @change="_batchUpdate($event)"
              accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              type="file"
            />
          </a>
          <span v-if="tips" class="errortext">请选择需要导入的Excel文件</span>
          <span>导入规则说明：文件后缀名必须为：xls 或xlsx （即Excel格式）</span>
        </ul>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="_cancel" size="small">取 消</el-button>
        <el-button type="primary" @click="_uploadbutton()" size="small">上传</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from "vuex";
import util from "@/util";
import u from "@/util/state";
import { TableHandle } from "@/util/class";
import pageUnit from "components/Page";
import axios from "axios";
import {
  getGoodsLabelListByShopId,
  selectShopTypeList,
  listUnifyPrice,
  listPriceDetail,
  saveUpdatePrice,
  exportUnifyPrice,
  deletePrice
} from "@/api";
var fileDownload = require("js-file-download");
export default {
  computed: mapState([
    "sub",
    "merchantId",
    "power",
    "userId",
    "linkName",
    "mobile",
    "token"
  ]),
  components: { pageUnit },
  data() {
    return {
      commodityBrandList: [], // 商品品牌
      shopTypesList: [], //客户名称
      clientsalePrice: {
        shopName: "",
        brandId: "",
        shopTypeIds: ""
      },
      // 调价历史外弹窗
      orderTable: new TableHandle(), //添加历史
      pricemange: new TableHandle(), //统一价格
      addprice: new TableHandle(), //新增调价
      batchUpdate: new TableHandle(), //批量更新
      uploadin: new TableHandle(), //上传中弹窗
      // 新增调价
      rules: {
        effectiveperiod: [
          {
            required: true,
            message: "请选择日期",
            trigger: "change"
          }
        ],
        interimprice: [
          { required: true, message: "请输入期间价格", trigger: "blur" },
          {
            validator: util.valida,
            trigger: "blur"
          },
          {
            validator: util.validateOperatingArea,
            trigger: "blur"
          },
          {
            validator: util.validatenum1,
            trigger: "blur"
          }
        ],
        pricereason: [
          { required: true, message: "请输入调价原因", trigger: "blur" }
        ]
      },
      ruleForm: {
        effectiveperiod: [],
        interimprice: "",
        pricereason: ""
      },
      data: {}, //导出的参数
      tips: false, //上传文件提示语
      files: {}, //上传文件
      value: "请上传文件",
      speedofprogress: 20,
      priceId: "", //调价历史id
      hispricelist: {
        barCode: "",
        goodsCode: ""
      }, //调价历史数据
      pricestatusList: ["未生效", "已生效", "已过期"],
      users: "",
      url: "",
      submin: false
    };
  },
  mounted() {
    this._pricemangeListPage(this.pricemange.pageData.pageSize, 1);
    this.commodityBrand();
    this.getShopTypeList();
    this.init();
  },
  watch: {
    sub: {
      handler: function(val, oldVal) {
        if (oldVal != null && val == false) {
          this._pricemangeListPage(this.pricemange.pageData.pageSize, 1);
        }
      },
      deep: true
    }
  },
  methods: {
    init() {
      this.href = window.location.href;
      // this.href="http://re.mumzone.cn/merchant/#/operate-management/client-management/unifiedprice-management"
      let hrefs = this.href.split("//")[1].split(".")[0];
      let token = this.token;
      if (hrefs == "re") {
        this.url =
          "http://re.mumzone.cn/egg_order/api/v1/order/listUpUnifyPrice";
      } else if (hrefs == "business") {
        this.url =
          "http://service.mumzone.cn/egg_order/api/v1/order/listUpUnifyPrice";
      } else {
        // this.url ="http://192.168.1.245:8045/api/v1/order/listUpUnifyPrice"
        this.url =
          "http://test3.mumzone.cn/egg_order/api/v1/order/listUpUnifyPrice";
      }
      if (this.linkName == undefined || this.linkName == "") {
        this.users = this.mobile;
      } else {
        this.users = this.linkName;
      }
    },
    //配置权限
    setRole(key) {
      return util.selectTitle(this.power, key);
    },
    // 商品品牌
    commodityBrand() {
      getGoodsLabelListByShopId({
        labelType: "0",
        shopId: this.merchantId
      }).then(res => {
        this.commodityBrandList = res.data.list;
      });
    },
    // 客户类型
    getShopTypeList() {
      let data = {
        shopId: this.merchantId,
        name: "",
        status: 0
      };
      selectShopTypeList(data).then(res => {
        if (res.code == 200) {
          this.shopTypesList = res.data;
        }
      });
    },
    // 统一价格列表
    _pricemangeListPage(pageSize, pageNum) {
      let data = {
        pageNum: pageNum,
        pageSize: pageSize,
        shopId: this.merchantId,
        goodsLabelId: this.clientsalePrice.brandId,
        shopTypeId: this.clientsalePrice.shopTypeIds,
        goodsName: this.clientsalePrice.shopName
      };
      this.data = data;
      listUnifyPrice(data).then(res => {
        this.pricemange.tableData = res.data.list;
        this.pricemange.tableData.forEach(ele => {
          ele.entryTime = [];
          ele.timobj = {};
          ele.timobj.startDate = util.foryear(ele.startDate);
          ele.timobj.endDate = util.foryear(ele.endDate);
          ele.entryTime.push(ele.timobj);
        });
        this.pricemange.pageData.totalItems = res.data.pageTotal;
      });
    },
    // 查询按钮
    counsearch() {
      this._pricemangeListPage(this.pricemange.pageData.pageSize, 1);
    },
    update() {
      this.batchUpdate.dialog = true;
    },
    // 批量更新
    _batchUpdate(event) {
      // console.log(location.reload())
      this.file = event.target.files[0]; //获取文件
      var windowURL = window.URL || window.webkitURL;
      //创建图片文件的url
      this.src = windowURL.createObjectURL(event.target.files[0]);
      //取消默认行为
      event.preventDefault();
      this.files = this.file;
      this.value = this.file.name;
    },
    // 上传取消
    _cancel() {
      this.batchUpdate.dialog = false;
      if (this.value != "请上传文件") {
        location.reload();
      }
    },
    // 上传
    _uploadbutton() {
      if (this.value == "请上传文件") {
        this.tips = true;
      } else {
        this.tips = false;
        this.uploadin.dialog = true;
        let formdata = new FormData();
        formdata.append("file", this.files);
        formdata.append("shopId", this.merchantId);
        formdata.append("creater", this.users);

        this.loading = true;
        let self = this;
        axios
          .post(this.url + "?token=" + this.token, formdata, {
            headers: {
              "Content-Type": "multipart/form-data"
            },
            transformRequest: [
              function(data) {
                return data;
              }
            ],
            onUploadProgress: progressEvent => {
              let complete =
                ((progressEvent.loaded / progressEvent.total) * 100) | 0;
              self.speedofprogress = complete;
            }
          })
          .then(res => {
            if (res.data.code == 200) {
              this.uploadin.dialog = false;
              this.$refs.uploading.value = null;
              this.loading = false;
              // this.value = "请上传文件"
              location.reload();
              this.files = "";
              this.file = "";
              this._pricemangeListPage(this.pricemange.pageData.pageSize, 1);
              this.$message({
                showClose: true,
                message: "上传成功",
                type: "success"
              });
            } else if (res.data.code == "10001") {
              let url = "";
              this.uploadin.dialog = false;
              this.$message.error("有错误数据未上传成功，已在表格返回错误信息");
              window.open((url = res.data.msg));
            } else {
              this.uploadin.dialog = false;
              self.speedofprogress = 20;
              // this.$message({
              //   showClose: true,
              //   message: "上传失败(请按照使用说明修改后上传)",
              //   type: "error"
              // });
            }
          })
          .catch(error => {})
          .finally((this.$refs.uploading.value = null));
      }
    },
    // 导出
    download() {
      if (this.pricemange.tableData.length == "0") {
        this.$message.error("数据为空不能导出");
      } else {
        exportUnifyPrice(this.data).then(res => {
          let time = new Date();
          let fileName = "统一价格管理表 " + util.getdatetime(time) + ".xlsx";
          fileDownload(res, fileName);
        });
      }
    },
    routerPush() {
      util.routerTo(
        "/operate-management/client-management/unifiedprice-management/audit-records"
      );
    },
    //转时间戳
    tim(row, column) {
      return util.foryear(row.startDate);
    },
    tim1(row, column) {
      return util.foryear(row.createTime);
    },
    addpriceButton() {
      this.addprice.dialog = true;
      this.ruleForm.effectiveperiod = [];
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.status == 1) {
        return "warning-row";
      }
      return "";
    },
    // 删除调价历史
    deletes(index, rows) {
      let text;
      if (rows.status == "1") {
        text = "当前期间价格生效中，是否确认删除";
      } else {
        text = "";
      }
      this.$confirm(text, "确认删除？", {
        center: true,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        closeOnClickModal: false,
        closeOnPressEscape: false
      })
        .then(() => {
          let data = {
            detailId: rows.detailId
          };
          deletePrice(data).then(res => {
            if (res.code == "200") {
              this._pricehistoryListPage(1);
              this._pricemangeListPage(this.pricemange.pageData.pageSize, 1);
              this.$message({
                type: "success",
                message: res.msg
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 调价历史
    _pricehistory(index, rows) {
      this.orderTable.dialog = true;
      this.priceId = rows.id;
      this._pricehistoryListPage(1);
    },
    // 调价历史弹窗
    _pricehistoryListPage(id) {
      listPriceDetail({
        id: this.priceId,
        creater: ""
      }).then(res => {
        this.hispricelist = res.data;
        this.orderTable.tableData = res.data.priceList;
        this.orderTable.tableData.forEach(ele => {
          ele.entryTime = [];
          ele.timobj = {};
          ele.timobj.startDate = util.foryear(ele.startDate);
          ele.timobj.endDate = util.foryear(ele.endDate);
          ele.entryTime.push(ele.timobj);
        });
        this.orderTable.pageData.totalItems = res.data.pageTotal;
      });
    },
    // 新增调价保存
    submitForm(formName) {
      this.submin = true;
      this.$refs[formName].validate(valid => {
        if (valid) {
          saveUpdatePrice({
            unifyPriceId: this.priceId,
            price: this.ruleForm.interimprice,
            startDate: this.ruleForm.effectiveperiod[0],
            endDate: this.ruleForm.effectiveperiod[1],
            remark: this.ruleForm.pricereason,
            creater: this.users
          }).then(res => {
            this.submin = false;
            if (res.code == "200") {
              this._pricehistoryListPage(1);
              this.itins();
              this.addprice.dialog = false;
            }
          });
        } else {
          this.submin = false;
          return false;
        }
      });
    },
    itins() {
      this.ruleForm.interimprice = "";
      this.ruleForm.effectiveperiod[0] = "";
      this.ruleForm.effectiveperiod[1] = "";
      this.ruleForm.pricereason = "";
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>
<style scoped>
.pltable /deep/ .el-table .warning-row {
  background: oldlace;
}
.billdata .el-date-editor .el-range__close-icon {
  display: none;
}
.updatetext span {
  font-size: 15px;
  margin-top: 10px;
  display: block;
}
.updatetext li {
  font-size: 13px;
  margin-top: 5px;
}
.file {
  position: relative;
  top: 10px;
  display: inline-block;
  background: #fff;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 4px 12px;
  margin: auto 10px;
  overflow: hidden;
  color: #333;
  text-decoration: none;
  text-indent: 0;
  line-height: 18px;
  font-size: 10px;
  width: 200px;
  height: 20px;
}
.file input {
  position: absolute;
  right: 0;
  top: 0;
  opacity: 0;
}
.file:hover {
  background: #fff;
  border-color: #ccc;
  color: #333;
  text-decoration: none;
}
.errortext {
  color: red;
  font-size: 10px !important;
  margin-left: 20px;
}
.uploadin /deep/ .el-dialog__header {
  background-color: #ddd;
}
.uploadin /deep/ .el-dialog__body {
  background-color: #ddd;
}
.uploadin /deep/ .el-dialog__header .el-dialog__close {
  color: #ddd;
}
.uploadin {
  margin: 0 auto;
  text-align: center;
}
.uploadin .uploadintext {
  height: 80px;
  font-size: 18px;
}
</style>
